// 弹窗脚本
// 全局变量
let allAccounts = []; // 存储所有账号数据，用于搜索
let filteredAccounts = []; // 存储过滤后的账号数据

document.addEventListener('DOMContentLoaded', function() {
  console.log('弹窗已加载');
  
  // 确保DOM完全加载后再初始化
  setTimeout(() => {
    // 初始化
    injectCustomConfirmUI(); // 注入自定义弹窗UI
    initTabs();
    loadAccounts();
    loadSettings();
    setupAutoSave(); // 设置自动保存
    setupSearch(); // 设置搜索功能
    setupCleanup(); // 设置清理功能
  }, 100);
});

// 初始化标签切换
function initTabs() {
  const tabs = document.querySelectorAll('.tab');
  const contents = document.querySelectorAll('.tab-content');
  
  tabs.forEach(tab => {
    tab.addEventListener('click', function() {
      const tabName = this.dataset.tab;
      
      // 切换标签样式
      tabs.forEach(t => t.classList.remove('active'));
      this.classList.add('active');
      
      // 切换内容显示
      const searchContainer = document.getElementById('search-container-accounts');
      
      if (tabName === 'accounts') {
        document.getElementById('accounts-content').style.display = 'block';
        document.getElementById('settings-content').style.display = 'none';
        if (searchContainer) searchContainer.style.display = 'block';
      } else if (tabName === 'settings') {
        document.getElementById('accounts-content').style.display = 'none';
        document.getElementById('settings-content').style.display = 'block';
        if (searchContainer) searchContainer.style.display = 'none';
      }
    });
  });
}

// 加载账号列表
function loadAccounts() {
  chrome.runtime.sendMessage({action: 'getLoginAccounts'}, function(response) {
    if (response && response.accounts) {
      allAccounts = response.accounts; // 保存所有账号数据
      filteredAccounts = [...allAccounts]; // 初始化过滤后的数据
      displayAccounts(filteredAccounts);
    } else {
      allAccounts = [];
      filteredAccounts = [];
      showEmptyState();
    }
  });
}

// 显示账号列表
function displayAccounts(accounts) {
  const container = document.getElementById('accounts-list');
  
  if (accounts.length === 0) {
    showEmptyState();
    return;
  }
  
  // 按域名分组
  const groupedAccounts = {};
  accounts.forEach(account => {
    if (!groupedAccounts[account.hostname]) {
      groupedAccounts[account.hostname] = [];
    }
    groupedAccounts[account.hostname].push(account);
  });
  
  let html = '';
  
  // 遍历每个域名分组
  for (const hostname in groupedAccounts) {
    const domainAccounts = groupedAccounts[hostname];
    const defaultAccount = domainAccounts.find(acc => acc.isDefault);
    const accountCount = domainAccounts.length;
    
    // 获取该域名组第一个账号，用于显示别名
    const firstAccount = domainAccounts[0];
    const displayName = firstAccount.alias && firstAccount.alias.trim() ? firstAccount.alias : hostname;
    
    html += `
      <div class="domain-group">
        <div class="domain-header">
          <div>
            <div class="domain-name-container" style="display: flex; align-items: center; justify-content: start; gap: 8px; ">
              🌐 ${displayName}
              <button class="alias-edit-btn" data-action="editAlias" data-domain="${hostname}" title="编辑别名">✏️</button>
            </div>
            ${firstAccount.alias && firstAccount.alias.trim() ? `<div class="domain-url">${hostname}</div>` : ''}
          </div>
          <div style="text-align: right;">
            ${accountCount > 1 ? `<span style="font-size: 12px; opacity: 0.8;">${accountCount} 个账号</span>` : ''}
          </div>
        </div>
        <div class="domain-accounts">
    `;
    
    // 先显示默认账号，然后显示其他账号
    const sortedAccounts = domainAccounts.sort((a, b) => {
      if (a.isDefault && !b.isDefault) return -1;
      if (!a.isDefault && b.isDefault) return 1;
      return 0;
    });
    
    sortedAccounts.forEach(account => {
      html += `
        <div class="account-item ${account.isDefault ? 'default' : ''}">
          <div class="account-info clickable" data-action="openAndLogin" data-hostname="${hostname}" data-domain="${account.domain}" data-loginId="${account.loginId}" title="点击打开并使用此账号登录">
            <div class="account-login">
              (${account.domain}) ${account.loginId}
              ${account.isDefault && accountCount > 1 ? '<span class="default-badge">默认</span>' : ''}
            </div>
          </div>
          <div class="account-actions">
            <button class="btn btn-secondary" data-action="openAndLogin" data-hostname="${hostname}" data-domain="${account.domain}" data-loginId="${account.loginId}" title="打开并使用此账号登录">打开</button>
            ${!account.isDefault && accountCount > 1 ? `<button class="btn btn-primary" data-action="setDefault" data-hostname="${hostname}" data-domain="${account.domain}" data-loginId="${account.loginId}" title="设为默认账号">设为默认</button>` : ''}
            <button class="btn btn-danger" data-action="delete" data-hostname="${hostname}" data-domain="${account.domain}" data-loginId="${account.loginId}" title="删除账号">删除</button>
          </div>
        </div>
      `;
    });
    
    html += `
        </div>
      </div>
    `;
  }
  
  container.innerHTML = html;
  
  // 设置事件委托处理按钮点击
  setupAccountActions();
}

// 设置账号操作事件委托
function setupAccountActions() {
  const container = document.getElementById('accounts-list');
  
  // 移除之前的事件监听器（如果存在）
  container.removeEventListener('click', handleAccountAction);
  
  // 添加事件委托
  container.addEventListener('click', handleAccountAction);
}

// 处理账号操作
function handleAccountAction(event) {
  // 查找具有 data-action 属性的元素（包括按钮和其他可点击元素）
  const actionElement = event.target.closest('[data-action]');
  if (!actionElement) return;
  
  const action = actionElement.dataset.action;
  const hostname = actionElement.dataset.hostname;
  const domain = actionElement.dataset.domain;
  const loginId = actionElement.dataset.loginid;
  
  console.log('元素点击:', action, { hostname, domain, loginId });
  
  switch (action) {
    case 'openAndLogin':
      if (hostname && domain && loginId) {
        openAndLogin(hostname, domain, loginId);
      }
      break;
    case 'setDefault':
      if (hostname && domain && loginId) {
        setDefault(hostname, domain, loginId);
      }
      break;
    case 'delete':
      if (hostname && domain && loginId) {
        deleteAccount(hostname, domain, loginId);
      }
      break;
    case 'editAlias':
      if (domain) {
        editAlias(domain);
      }
      break;
  }
}

// 显示空状态
function showEmptyState() {
  const container = document.getElementById('accounts-list');
  container.innerHTML = `
    <div class="empty-state">
      <div class="icon">🔐</div>
      <h3 style="margin: 16px 0 8px 0; color: #333;">还没有保存的登录信息</h3>
      <p style="margin: 0 0 16px 0; color: #666; line-height: 1.5;">
        在网站上登录后，插件会自动保存您的登录信息<br>
        支持按域名分组管理，方便快速切换账号
      </p>
      <div style="background: #f8f9fa; padding: 12px; border-radius: 6px; font-size: 12px; color: #666;">
        💡 <strong>小提示：</strong> 您可以为每个域名设置多个账号，并选择默认账号用于自动登录。还可以为域名设置别名，方便识别
      </div>
    </div>
  `;
}

// 打开并登录
function openAndLogin(hostname, domain, loginId) {
  const account = allAccounts.find(acc => acc.hostname === hostname && acc.domain === domain && acc.loginId === loginId);
  if (account) {
    console.log('请求打开并登录:', account);
    chrome.runtime.sendMessage({ action: 'openAndLogin', account: account }, () => {
      window.close(); // 发送消息后关闭弹窗
    });
  }
}

// 打开新标签页
function openTab(url) {
  console.log('尝试打开页面:', url);
  
  chrome.runtime.sendMessage({
    action: 'openTab',
    url: url
  }, function(response) {
    console.log('打开页面响应:', response);
    if (response && response.success) {
      console.log('页面打开成功，关闭弹窗');
      window.close(); // 关闭弹窗
    } else {
      console.error('页面打开失败');
    }
  });
}

// 设置默认账号
function setDefault(hostname, domain, loginId) {
  console.log('设置默认账号:', hostname, domain, loginId);
  
  // 先获取该域名的所有账号
  chrome.storage.local.get([hostname], function(result) {
    let accounts = result[hostname] || [];
    console.log('当前账号列表:', accounts);
    
    // 将所有账号的isDefault设为false
    accounts.forEach(account => {
      account.isDefault = false;
    });
    
    // 设置指定账号为默认
    const targetAccount = accounts.find(acc => acc.hostname === hostname && acc.loginId === loginId && acc.domain === domain);
    if (targetAccount) {
      targetAccount.isDefault = true;
      console.log('找到目标账号，设置为默认:', targetAccount);
    } else {
      console.error('未找到目标账号:', loginId);
    }
    
    // 保存更新
    chrome.storage.local.set({[hostname]: accounts}, function() {
      console.log('默认账号设置已保存，重新加载列表');
      loadAccounts(); // 重新加载显示
      // 重新应用当前搜索
      const currentSearch = document.getElementById('host-search').value.trim();
      if (currentSearch) {
        setTimeout(() => performSearch(currentSearch), 100);
      }
    });
  });
}

// 编辑别名
function editAlias(domain) {
  console.log('编辑别名:', domain);
  
  // 获取当前域名的账号信息
  chrome.storage.local.get([domain], function(result) {
    const accounts = result[domain] || [];
    if (accounts.length === 0) return;
    
    const currentAlias = accounts[0].alias || '';
    const newAlias = prompt('请输入别名（留空则使用域名）:', currentAlias);
    
    if (newAlias !== null) { // 用户没有取消
      // 更新所有该域名下账号的别名
      accounts.forEach(account => {
        account.alias = newAlias.trim();
      });
      
      chrome.storage.local.set({[domain]: accounts}, function() {
        console.log('别名已更新');
        loadAccounts(); // 重新加载显示
        // 重新应用当前搜索
        const currentSearch = document.getElementById('host-search').value.trim();
        if (currentSearch) {
          setTimeout(() => performSearch(currentSearch), 100);
        }
      });
    }
  });
}

// 注入自定义确认弹窗的HTML和CSS
function injectCustomConfirmUI() {
  const css = `
    .confirm-modal-overlay {
      position: fixed; top: 0; left: 0; width: 100%; height: 100%;
      background: rgba(0, 0, 0, 0.4);
      display: none;
      align-items: center; justify-content: center;
      z-index: 1000;
    }

    @keyframes confirm-modal-animation {
      from {
        opacity: 0;
        transform: scale(0.95);
      }
      to {
        opacity: 1;
        transform: scale(1);
      }
    }

    .confirm-modal {
      background: white;
      width: 300px;
      border-radius: 12px;
      box-shadow: 0 5px 20px rgba(0,0,0,0.1);
      animation: confirm-modal-animation 0.2s ease-out;
      text-align: center;
    }

    .confirm-modal p {
      padding: 24px 24px 20px 24px;
      margin: 0;
      font-size: 16px;
      color: #333;
      line-height: 1.5;
    }

    .confirm-modal-actions {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      padding: 0 24px 24px;
    }

    .confirm-modal .btn {
      width: 100%;
      padding: 10px 16px;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s ease;
    }
    
    .confirm-modal .btn:active {
      transform: scale(0.97);
    }

    .confirm-modal .btn-secondary {
      background-color: #e9ecef;
      color: #495057;
    }
    
    .confirm-modal .btn-secondary:hover {
      background-color: #dee2e6;
    }

    .confirm-modal .btn-danger {
      background-color: #fa5252;
      color: white;
    }

    .confirm-modal .btn-danger:hover {
      transform: none;
      box-shadow: none;
    }

    /* Styles for account action buttons */
    .account-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .account-actions .btn {
      padding: 5px 12px;
      font-size: 12px;
      border-radius: 6px;
      border: 1px solid transparent;
      cursor: pointer;
      transition: all 0.2s ease;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .account-actions .btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }

    /* Primary button (Set Default) */
    .account-actions .btn-primary {
      background-color: #f1f3f5;
      color: #495057;
      border: 1px solid #dee2e6;
    }

    .account-actions .btn-primary:hover {
      background-color: #e9ecef;
      border-color: #ced4da;
    }

    /* Danger button (Delete) */
    .account-actions .btn-danger {
      background-color: #fa5252;
      color: white;
      border: 1px solid #fa5252;
    }

    .account-actions .btn-danger:hover {
      transform: none;
      box-shadow: none;
    }

    /* Clickable account info */
    .account-info.clickable {
      cursor: pointer;
    }
  `;
  const style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);

  const html = `
    <div id="custom-confirm-modal" class="confirm-modal-overlay">
      <div class="confirm-modal">
        <p id="confirm-modal-text"></p>
        <div class="confirm-modal-actions">
          <button id="confirm-cancel-btn" class="btn btn-secondary">取消</button>
          <button id="confirm-ok-btn" class="btn btn-danger">确定</button>
        </div>
      </div>
    </div>
  `;
  document.body.insertAdjacentHTML('beforeend', html);
}

// 显示自定义确认弹窗
function showCustomConfirm(message, onConfirm) {
  const modal = document.getElementById('custom-confirm-modal');
  const modalText = document.getElementById('confirm-modal-text');
  const okBtn = document.getElementById('confirm-ok-btn');
  const cancelBtn = document.getElementById('confirm-cancel-btn');

  modalText.textContent = message;
  modal.style.display = 'flex';

  const okHandler = () => {
    modal.style.display = 'none';
    onConfirm(true);
    cleanup();
  };

  const cancelHandler = () => {
    modal.style.display = 'none';
    onConfirm(false);
    cleanup();
  };

  const cleanup = () => {
    okBtn.removeEventListener('click', okHandler);
    cancelBtn.removeEventListener('click', cancelHandler);
  };

  okBtn.addEventListener('click', okHandler);
  cancelBtn.addEventListener('click', cancelHandler);
}

// 删除账号
function deleteAccount(hostname, domain, loginId) {
  console.log('删除账号:', hostname, domain, loginId);
  
  showCustomConfirm('确定要删除这个登录账号吗？', (confirmed) => {
    if (confirmed) {
      console.log('用户确认删除');
      chrome.runtime.sendMessage({
        action: 'deleteAccount',
        hostname: hostname,
        domain: domain,
        loginId: loginId
      }, function(response) {
        console.log('删除账号响应:', response);
        if (response && response.success) {
          console.log('账号删除成功，重新加载列表');
          loadAccounts(); // 重新加载显示
          // 重新应用当前搜索
          const currentSearch = document.getElementById('host-search').value.trim();
          if (currentSearch) {
            setTimeout(() => performSearch(currentSearch), 100);
          }
        } else {
          console.error('账号删除失败');
        }
      });
    } else {
      console.log('用户取消删除');
    }
  });
}

// 加载设置
function loadSettings() {
  console.log('开始加载设置');
  chrome.storage.local.get([ 'enableAutoLogin', 'enableNotifications', 'enableLoginCheck', 'signOutCooldown', 'enableQrCodeFeature'], function(result) {
    console.log('从storage加载的设置:', result);
    
    const enableAutoLogin = result.enableAutoLogin !== undefined ? result.enableAutoLogin : true;
    const enableNotifications = result.enableNotifications !== undefined ? result.enableNotifications : true;
    const enableLoginCheck = result.enableLoginCheck !== undefined ? result.enableLoginCheck : true;
    const signOutCooldown = result.signOutCooldown !== undefined ? result.signOutCooldown : 2;
    const enableQrCodeFeature = result.enableQrCodeFeature !== undefined ? result.enableQrCodeFeature : true;
    
    // 应用到界面
    document.getElementById('enableAutoLogin').checked = enableAutoLogin;
    document.getElementById('enableNotifications').checked = enableNotifications;
    document.getElementById('enableLoginCheck').checked = enableLoginCheck;
    document.getElementById('signOutCooldown').value = signOutCooldown;
    document.getElementById('enableQrCodeFeature').checked = enableQrCodeFeature;
    
    console.log('设置已应用到界面');
  });
}

// 监听窗口关闭前事件，确保用户输入不丢失
window.addEventListener('beforeunload', function() {
  console.log('popup即将关闭');
});

// 添加输入变化监听，自动保存设置
function setupAutoSave() {
  const settingInputs = [
    'enableAutoLogin', 
    'enableNotifications',
    'enableLoginCheck',
    'signOutCooldown',
    'enableQrCodeFeature'
  ];
  
  settingInputs.forEach(inputId => {
    const element = document.getElementById(inputId);
    if (element) {
      // 为文本输入框添加延迟保存
      if (element.type === 'text' || element.type === 'number') {
        let timeoutId;
        element.addEventListener('input', function() {
          clearTimeout(timeoutId);
          timeoutId = setTimeout(() => {
            console.log('自动保存设置触发:', inputId);
            saveSettingsQuietly();
          }, 1000); // 1秒后自动保存
        });
      }
      // 为复选框添加立即保存
      else if (element.type === 'checkbox') {
        element.addEventListener('change', function() {
          console.log('复选框变化自动保存:', inputId);
          
          // 特别处理二维码功能设置
          if (inputId === 'enableQrCodeFeature') {
            const enabled = this.checked;
            console.log('二维码功能设置变化:', enabled);
            
            // 立即保存并通知background
            const settingsToSave = {
              enableQrCodeFeature: enabled
            };
            
            chrome.storage.local.set(settingsToSave, function() {
              if (!chrome.runtime.lastError) {
                console.log('二维码功能设置已保存，将由background自动通知所有标签页');
                // background.js会监听storage变化并自动向所有标签页发送切换消息
              } else {
                console.error('保存二维码功能设置失败:', chrome.runtime.lastError);
              }
            });
          } else {
            saveSettingsQuietly();
          }
        });
      }
    }
  });
}

// 静默保存设置（不显示提示）
function saveSettingsQuietly() {
  const enableAutoLogin = document.getElementById('enableAutoLogin').checked;
  const enableNotifications = document.getElementById('enableNotifications').checked;
  const enableLoginCheck = document.getElementById('enableLoginCheck').checked;
  const signOutCooldown = document.getElementById('signOutCooldown').value;
  const enableQrCodeFeature = document.getElementById('enableQrCodeFeature').checked;
  
  const settingsToSave = {
    enableAutoLogin: enableAutoLogin,
    enableNotifications: enableNotifications,
    enableLoginCheck: enableLoginCheck,
    signOutCooldown: parseInt(signOutCooldown),
    enableQrCodeFeature: enableQrCodeFeature
  };
  
  chrome.storage.local.set(settingsToSave, function() {
    if (!chrome.runtime.lastError) {
      console.log('设置已自动保存');
    }
  });
}

// 设置搜索功能
function setupSearch() {
  const searchInput = document.getElementById('host-search');
  const clearButton = document.getElementById('clear-search');
  const searchIcon = document.querySelector('.search-icon');
  const resultsInfo = document.getElementById('search-results-info');
  
  if (!searchInput) return;
  
  let searchTimeout;
  
  // 搜索输入事件
  searchInput.addEventListener('input', function() {
    const query = this.value.trim();
    
    // 显示/隐藏清除按钮
    if (query) {
      clearButton.style.display = 'block';
      searchIcon.style.display = 'none';
    } else {
      clearButton.style.display = 'none';
      searchIcon.style.display = 'block';
    }
    
    // 防抖搜索
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
      performSearch(query);
    }, 300);
  });
  
  // 清除搜索
  clearButton.addEventListener('click', function() {
    searchInput.value = '';
    clearButton.style.display = 'none';
    searchIcon.style.display = 'block';
    resultsInfo.style.display = 'none';
    performSearch('');
  });
  
  // 回车键搜索
  searchInput.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
      clearTimeout(searchTimeout);
      performSearch(this.value.trim());
    }
  });
}

// 执行搜索
function performSearch(query) {
  const resultsInfo = document.getElementById('search-results-info');
  
  if (!query) {
    // 没有搜索词，显示所有账号
    filteredAccounts = [...allAccounts];
    resultsInfo.style.display = 'none';
  } else {
    // 进行搜索过滤
    const lowerQuery = query.toLowerCase();
    filteredAccounts = allAccounts.filter(account => {
      // 搜索域名、别名和登录ID
      return account.hostname.toLowerCase().includes(lowerQuery) || 
             account.loginId.toLowerCase().includes(lowerQuery) ||
             (account.alias && account.alias.toLowerCase().includes(lowerQuery));
    });
    
    // 显示搜索结果信息
    const totalCount = allAccounts.length;
    const filteredCount = filteredAccounts.length;
    
    if (filteredCount === 0) {
      resultsInfo.textContent = `未找到包含 "${query}" 的账号`;
      resultsInfo.style.color = '#ff6b6b';
    } else if (filteredCount === totalCount) {
      resultsInfo.style.display = 'none';
    } else {
      resultsInfo.textContent = `找到 ${filteredCount} 个账号，共 ${totalCount} 个`;
      resultsInfo.style.color = '#666';
    }
    resultsInfo.style.display = 'block';
  }
  
  // 显示过滤后的结果
  if (filteredAccounts.length === 0 && query) {
    showSearchEmptyState(query);
  } else if (filteredAccounts.length === 0) {
    showEmptyState();
  } else {
    displayAccounts(filteredAccounts);
  }
}

// 显示搜索无结果状态
function showSearchEmptyState(query) {
  const container = document.getElementById('accounts-list');
  container.innerHTML = `
    <div class="empty-state">
      <div class="icon">🔍</div>
      <h3 style="margin: 16px 0 8px 0; color: #333;">未找到相关账号</h3>
      <p style="margin: 0 0 16px 0; color: #666; line-height: 1.5;">
        没有找到包含 "<strong>${query}</strong>" 的域名或账号<br>
        请尝试其他关键词进行搜索
      </p>
      <div style="background: #f8f9fa; padding: 12px; border-radius: 6px; font-size: 12px; color: #666;">
        💡 <strong>搜索提示：</strong> 可以搜索域名（如：github.com）或账号名称
      </div>
    </div>
  `;
}

// 全局函数，供HTML调用
window.openTab = openTab;
window.setDefault = setDefault;
window.deleteAccount = deleteAccount; 

// 设置清理功能
function setupCleanup() {
  // 创建清理按钮（如果不存在）
  let cleanupBtn = document.getElementById('cleanup-invalid-accounts');
  if (!cleanupBtn) {
    // 在设置页面添加清理按钮
    const settingsContent = document.getElementById('settings-content');
    if (settingsContent) {
      const cleanupSection = document.createElement('div');
      cleanupSection.innerHTML = `
        <div style="border-top: 1px solid #eee; padding-top: 15px; margin-top: 15px;">
          <h3 style="margin: 0 0 10px 0; font-size: 14px;">数据清理</h3>
          <button id="cleanup-invalid-accounts" style="
            background: #ff4444; color: white; border: none; padding: 8px 12px; 
            border-radius: 4px; cursor: pointer; font-size: 12px;
          ">清理无效账号</button>
          <p style="font-size: 11px; color: #666; margin: 5px 0 0 0;">
            清理包含undefined或无效数据的账号
          </p>
        </div>
      `;
      settingsContent.appendChild(cleanupSection);
      cleanupBtn = document.getElementById('cleanup-invalid-accounts');
    }
  }
  
  if (cleanupBtn) {
    cleanupBtn.addEventListener('click', cleanupInvalidAccounts);
  }
}

// 清理无效账号
function cleanupInvalidAccounts() {
  console.log('开始清理无效账号...');
  
  chrome.storage.local.get(null, function(allData) {
    let cleanedCount = 0;
    const updates = {};
    
    Object.keys(allData).forEach(key => {
      // 跳过非账号数据
      if (key === 'settings' || key === 'uIdToken' || key === 'enableQrCodeFeature' || 
          key === 'qrShareIconPosition' || key === 'floatingIconPosition') {
        return;
      }
      
      const accounts = allData[key];
      if (Array.isArray(accounts)) {
        // 过滤掉无效账号
        const validAccounts = accounts.filter(account => {
          const isValid = account.loginId && 
                          account.loginId !== 'undefined' && 
                          account.domain && 
                          account.domain !== 'undefined' &&
                          account.hostname &&
                          account.hostname !== 'undefined';
          
          if (!isValid) {
            console.log('发现无效账号:', account);
            cleanedCount++;
          }
          
          return isValid;
        });
        
        // 如果清理后数组为空，删除整个键
        if (validAccounts.length === 0) {
          updates[key] = null; // 标记为删除
        } else if (validAccounts.length !== accounts.length) {
          updates[key] = validAccounts; // 更新为清理后的数组
        }
      }
    });
    
    // 应用更新
    if (Object.keys(updates).length > 0) {
      // 删除标记为null的键
      const keysToRemove = Object.keys(updates).filter(key => updates[key] === null);
      if (keysToRemove.length > 0) {
        chrome.storage.local.remove(keysToRemove, function() {
          console.log('已删除空的域名键:', keysToRemove);
        });
      }
      
      // 更新其他键
      const dataToUpdate = {};
      Object.keys(updates).forEach(key => {
        if (updates[key] !== null) {
          dataToUpdate[key] = updates[key];
        }
      });
      
      if (Object.keys(dataToUpdate).length > 0) {
        chrome.storage.local.set(dataToUpdate, function() {
          console.log('已更新账号数据:', dataToUpdate);
        });
      }
      
      // 显示结果
      alert(`清理完成！共清理了 ${cleanedCount} 个无效账号。`);
      
      // 重新加载账号列表
      setTimeout(() => {
        loadAccounts();
      }, 500);
      
    } else {
      alert('没有发现需要清理的无效账号。');
    }
  });
} 